// pages/client_follow_update/client_follow_update.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    optionsList: {

    },
    fieldList:[
      {field_id: 'followup_type_row_id',field_name: 'followup_type_name',type: 'picklist', optionList: [],optionId: 'row_id',optionName: 'followup_type_alias',showFlag: false,iconDown: false},
      {field_id: 'followup_tag_row_id',field_name: 'followup_tag_name',type: 'picklist', optionList: [],optionId: 'row_id',optionName: 'followup_tag_name',showFlag: false},
      {field_id: 'followup_progress_row_id',field_name: 'followup_progress_name',type: 'picklist', optionList: [],optionId: 'row_id',optionName: 'followup_progress_alias',showFlag: false},
      {field_id: 'order_client_id',field_name: 'order_client_name',type: 'picklist', optionList: [],optionId: 'id',optionName: 'name',showFlag: false},
      {field_id: 'followup_table_id',field_name: 'followup_table_name',type: 'picklist', optionList: [],optionId: 'table_id',optionName: 'table_name',showFlag: false},
      {field_id: 'followup_datetime',field_name: 'followup_datetime',type: 'datetime',showFlag: false,length: 'yyyy-MM-dd'},
      {field_id: 'user_list',type: 'picklist',showFlag: false, optionList: [],optionId: 'id',optionName: 'name'},
    ],
    //显示数据
    showData: {},
    //提交数据
    formData: {
      followup_type_row_id: '',
      followup_tag_row_id: '',
      followup_progress_row_id: '',
      order_client_id: '',
      followup_table_id: '',
      followup_datetime: '',
      followup_data_row_id: '',
      followup_data_order_no: '',
      row_id: 0
    },
    //业务单参数
    business:{
      mainEntity: 'e_xiaoshouruku ',
      flag: false,
      showFields: 'Order_No,Order_client_ID,abstract,Order_date,salesman',
      filter: ''
    },
    //@人员列表
    atUserList: [],
    //跟进内容
    followContent: '',
    //跟进内容输入框获取焦点
    followContentFocus: false,
    //图片
    pictureList: [],
    //附件
    fileList: [],

    //审批标识
    approveFlag: true,
    approveDis: false
  },

  //显示下拉
  showSelect(e){
    let {f_index} = e.currentTarget.dataset,
      {fieldList,business} = this.data;

    fieldList[f_index].showFlag = !fieldList[f_index].showFlag;
    //跟进类型
    if (f_index == 0){
      fieldList[f_index].iconDown = true;
    }
    this.setData({fieldList});

  },
  //隐藏下拉
  hideSelect(e){
    let {id} = e.currentTarget.dataset,
      {fieldList,business} = this.data;
    if (id === 'followup_type_row_id') {
      fieldList[0].iconDown = false;
      this.setData({fieldList});
    }
    if (id === 'followup_data_order_no') {
      fieldList[4].showFlag = !fieldList[4].showFlag;
      this.setData({fieldList});
    }
  },
  //选中
  bindSelect(e){
    let {id,f_index} = e.currentTarget.dataset,
      detail = e.detail,
      {fieldList, showData, formData} = this.data,
      fieldData = fieldList[f_index],
      setObj = {};

    //用户列表@人员
    if (fieldData.field_id === 'user_list'){
      this.selectUser(detail);
      return;
    }

    if (fieldData.type === 'picklist'){
      showData[fieldData.field_name] = detail[fieldData.optionName];
      formData[fieldData.field_id] = detail[fieldData.optionId];
      setObj = {showData,formData};
      //跟进类型，改变图标样式
      if (f_index === 0){
        fieldData.iconDown = false;
        setObj = {...setObj,fieldList};
      }
      //跟进客户，修改后清空已选业务单
      if (f_index === 3){
        showData.followup_data_order_no = '';
        formData.followup_data_row_id = '';
      }
      //跟进模块，选择后加载业务单列表
      if (f_index === 4 && detail.table_id !== 'customer'){
        let {business} = this.data;
        business.mainEntity = detail.table_id;
        business.flag = !business.flag;
        showData.followup_data_order_no = '';
        formData.followup_data_order_no = '';
        formData.followup_data_row_id = '';
        if (formData.order_client_id) {
          business.filter = JSON.stringify({filters:[{
              "fieldName": detail.table_id + ".Order_client_ID",
              "operator": "=",
              "value": formData.order_client_id,
              "or": 0
            }],type: 'AND'});
        }
        setObj = {...setObj,business};

      }
    }
    if (fieldData.type === 'datetime'){
      showData[fieldData.field_name] = detail;
      formData[fieldData.field_id] = detail;
      setObj = {showData,formData};
    }
    this.setData(setObj);
  },
  //选择关联业务
  selectCols(e){
    let {id,f_index} = e.currentTarget.dataset,
      detail = e.detail,
      {showData, formData} = this.data,
      val = detail.val;
    showData.followup_data_order_no = val.Order_No || val.order_no;
    formData.followup_data_order_no = val.Order_No || val.order_no;
    formData.followup_data_row_id = val.row_id;

    this.setData({showData,formData})
  },
  //清空选项
  clearIpt(e){
    let {id,f_index} = e.currentTarget.dataset,
      {fieldList, showData, formData} = this.data,
      fieldData = fieldList[f_index];
    showData[fieldData.field_name] = '';
    formData[fieldData.field_id] = '';
    if (fieldData.field_id === 'followup_table_id') {
      showData.followup_data_order_no = '';
      formData.followup_data_order_no = '';
    }
    this.setData({showData,formData});

    },
  //输入跟进内容
  bindinput(e){
    let {fieldList, followContent} = this.data,
      inputValue = e.detail.value,
      last = inputValue.substring(followContent.length);
    if (last === '@'){
      wx.hideKeyboard();
      this.setData({
        ['fieldList[6].showFlag']: !fieldList[6].showFlag
      })
    }else {
      this.setData({
        followContent: inputValue
      })
    }

  },
  //选择用户
  selectUser(detail){
    let {followContent,atUserList} = this.data;
    let isexist = atUserList.some(item=>{
      item.id === detail.id
    });
    if (!isexist) {
      atUserList.push(detail);
    }
    followContent += '@'+ detail.name;
    this.setData({
      followContent,
      followContentFocus: true
    });
  },
  //上传图片、附件
  chooseUpload(e){
    let {type} = e.currentTarget.dataset,
      {pictureList,fileList} = this.data;

    if(type === 'picture') {
      let len = 9 - pictureList.length
      if(!len) return
      wx.chooseMedia({
        count: len,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          let files = res.tempFiles,
            proArr = []
          files.forEach(item => {
            proArr.push(wx.$uploadReq(item.tempFilePath, ))
          })

          Promise.all(proArr).then(res => {
            res.forEach(item => {
              let { data, response, } = item,
                { errcode, } = response,
                { row, } = data
              if(errcode === 0 && row[0] && row[0].data) pictureList.push(row[0].data)
            })
            this.setData({
              pictureList,
            })
          })
        },
      })
    } else {
      let len = 9 - fileList.length
      if(!len) return
      wx.chooseMessageFile({
        count: len,
        type: 'all',
        success: (res) => {
          // tempFilePath可以作为 img 标签的 src 属性显示图片
          let files = res.tempFiles,
            proArr = []
          files.forEach(item => {
            proArr.push(wx.$uploadReq(item.path, item.name))
          })
          Promise.all(proArr).then(res => {
            res.forEach(item => {
              let { data, response, } = item,
                { errcode, } = response,
                { row, } = data
              if(errcode === 0 && row[0] && row[0].data) fileList.push(row[0].data)
            })
            this.setData({
              fileList,
            })
          })

        }
      })
    }
  },
  //预览图片
  previewImg(e){
    let current = e.currentTarget.dataset.src;
    wx.previewImage({
      current,
      urls: this.data.pictureList
    })
  },
  //删除图片、附件
  delUpload(e){
    let {type,index} = e.currentTarget.dataset,
      {pictureList, fileList} = this.data,
      name,msg,upload;
    if (type === 'picture') {
      msg = '确认删除该图片？';
      upload = pictureList;
      name = 'pictureList';
    }else {
      msg = '确认删除该附件？';
      upload = fileList;
      name = 'fileList';
    }

    wx.showModal({
      title: '提示',
      content: msg,
      success: (res) => {
        if(res.confirm) {
          upload.splice(index, 1)
          this.setData({
            [name]: upload,
          })
        }
      },
    })
  },

  //获取编辑数据
  getData(rid){
    let url = 'AllFollowup/query_all_followup',
      post = {
        "row_id": rid,
        "page": 1,
        "limit": 1};
    wx.$post(1,url,post).then(res=>{
      if (res.errcode != 0)return;
      let data = res.data.row[0];
      this.initEditData(data);
    });

    this.getApprovalProcess(rid).then((res)=>{
      //判断审批状态，可提交审批
      let {state,data} = res
      if (state !== '已同意' && state !== '已提交' && state !== '已重新提交' && state !== '待审' && !data){
        this.setData({
          approveDis: false,
          approveFlag:true
        })
      }else {
        this.setData({
          approveDis: true,
          approveFlag:false
        })
      }
    })
  },
  //初始化编辑数据
  initEditData(data){
    /*data = {
      "rowid": 9,
      // "row_id": 13,
      "system_id": 800,
      "input_id": "13827740413",
      "input_name": "卢生",
      "input_time": "2022-09-16 11:33:37",
      "modify_id": null,
      "modify_name": null,
      "modify_time": null,
      "followup_user_row_id": "33",
      "followup_user_name": "卢生",
      "followup_department_row_id": "2",
      "followup_department_name": "平台",
      "followup_datetime": "2022-09-16 11:33:37",
      "followup_type_row_id": "7",
      "followup_type_name": "线上跟踪别名",
      "followup_progress_row_id": "4",
      "followup_progress_name": "前期接触1",
      "followup_tag_row_id": "6",
      "followup_tag_name": "服务",
      "followup_content": "测试跟进<div class=\"pic-item\" contenteditable=\"false\" data-url=\"http://121.201.43.187:19054/files/75660bfc-405e-437b-b251-6e89eb874cf2_1608947159(1).jpg\"><img src=\"http://121.201.43.187:19054/files/75660bfc-405e-437b-b251-6e89eb874cf2_1608947159(1).jpg\" alt=\"\"></div><span contenteditable=\"false\" class=\"at-item\">@zhou</span><span contenteditable=\"false\" class=\"at-item\">@卢生</span><div class=\"file-item\" contenteditable=\"false\" title=\"1565083862(1).jpg\" data-url=\"http://121.201.43.187:19054/files/75660bfc-405e-437b-b251-6e89eb874cf2_1608947159(1).jpg\"><span class=\"file\">1565083862(1).jpg</span></div><div><div><div><div><br></div></div></div></div>",
      "Order_client_ID": "30",
      "order_client_name": "城市代理A",
      "followup_table_id": "e_ceshil",
      "followup_table_name": "测试l",
      "followup_data_row_id": "2",
      "followup_data_order_no": "2022-09-15-000002",
      "followup_at_json": null,
      "followup_expression_json": null,
      "followup_image_json": null,
      "followup_file_json": null,
      "followup_reply_total": null,
      "is_approval_process": true,
      "is_approval_process_self": false
    };*/
    let {formData} = this.data,
      setObj = {};
    setObj.showData = data;
    wx.$each(formData,(key,val)=>{
      if (key === 'order_client_id') {
        formData[key] = data.Order_client_ID || data.Order_client_ID;
      }else {
        data[key] && (formData[key] = data[key]);
      }
    });
    setObj.formData = formData;
    let content = data.followup_content,
      reg1 = /\<div(.+?)\<\/div\>/g,
      reg2 = /\<(.+?)\>/g,
      str = content.replace(reg1,'');  //替换网页端格式的html代码
    str = str.replace(reg2,'');
    setObj.followContent = str;
    //@人员
    if (data.followup_at_json){
      let atList = JSON.parse(data.followup_at_json);
      atList = atList.user;
      setObj.atUserList = atList;
    }
    //图片
    if (data.followup_image_json){
      let pictureList = JSON.parse(data.followup_image_json);
      setObj.pictureList = pictureList;
    }
    //附件
    if (data.followup_file_json){
      let fileList = JSON.parse(data.followup_file_json);
      setObj.fileList = fileList;
    }
    this.setData(setObj);
  },

  bindSubmit(e){
    let {type} = e.currentTarget.dataset;
    let {formData,progressRequired,tagRequire,atUserList,followContent, pictureList, fileList} = this.data;
    if (!followContent) {
      wx.$toast('请输入跟进内容！');return
    }
    let followup_content_string = followContent;

    if (tagRequire && !formData.followup_tag_row_id) {
      wx.$toast('标签不可为空！');return
    }
    if (progressRequired && !formData.followup_progress_row_id) {
      wx.$toast('跟进进度不可为空！');return
    }
    if (!formData.order_client_id) {
      wx.$toast('请选择客户！');return
    }
    if (formData.followup_table_id === 'customer'){
      formData.followup_data_row_id = formData.order_client_id;
    }

    if (formData.followup_table_id && !formData.followup_data_row_id){
      formData.followup_table_id = '';
      formData.followup_data_row_id = '';
      formData.followup_data_order_no = '';
    }

    //@人员
    let atList = [];
    wx.$each(atUserList,(i,item)=>{
      if (followup_content_string.indexOf('@' + item.name) >= 0){
        atList.push(item);
      }
    });
    if (atList.length>0){
      formData.followup_at_json = JSON.stringify({user: atList});
    }

    let followup_content = followup_content_string;
    //图片--转化网页端格式传入
    if (pictureList.length){
      pictureList.forEach(item=>{
        followup_content += `<div class="pic-item" contenteditable="false" data-url="${item}"><img src="${item}" alt=""></div>`
      });
      formData.followup_image_json = JSON.stringify(pictureList);
    }
    //附件--获取文件名称，转化网页端格式传入
    if (fileList.length){
      let filename = '';
      fileList.forEach(item=>{
        let name = item.split('_')[1];
        filename += name;
        followup_content += `<div class="file-item" contenteditable="false" title="${name}" data-url="${item}"><span class="file">${name}</span></div>`
      });
      followup_content_string += filename;
      formData.followup_file_json = JSON.stringify(fileList);
    }

    formData.followup_content = followup_content;
    formData.followup_content_string = followup_content_string;

    this.submitData(formData).then(()=>{
      wx.$toast('保存成功！');
      this.refreshList();
      if (type === 'close') {
        wx.navigateBack({ //跳转到前一个页面
          delta:1,//前一个页面
        });
      }else {
        //清空数据
        this.setData({
          formData: {row_id: 0},
          showData: {},
        });
        //清空审批数据
        this.approve && this.approve.setData({
          copyList:[],
          aprList: []
        })
      }
    })
  },
  //提交数据
  submitData(formData){
    let url = 'AllFollowup/update_all_followup';
    return new Promise(resolve => {
      wx.$post(1,url,formData).then(res=>{
        if (res.errcode != 0 )return;
        let rid = res.data.row[0] && res.data.row[0].row_id;
        this.data.formData.row_id = rid;
        if (this.data.approveFlag){
          this.approve = this.selectComponent('#approve');
          this.approve.submitFreeApproval(rid).then(()=>{
            resolve();
          });

        }else {
          resolve();
        }
      })
    })
  },


  //审批勾选
  toggleApprove(){
    this.setData({
      approveFlag: !this.data.approveFlag
    })
  },
  //获取审批内容判断是否显示审批
  getApprovalProcess(id){
    return new Promise(resolve => {
      let url = 'Approval_process/query_approval_process_log_group',
        post = {
          "page": 1,
          "limit": 1000,
          "oby": "input_time,step,log_row_id",
          "SearchWhere": [
            {
              "CompareWith": "table_id",
              "Operator": "=",
              "CompareValue": "all_followup",
              "or": 0
            },
            {
              "CompareWith": "row_id",
              "Operator": "=",
              "CompareValue": id,
              "or": 0
            },
            /*{
              "CompareWith": "1",
              "Operator": "=",
              "CompareValue": "(CASE WHEN step>1 AND sh_state='待审' THEN 0 ELSE 1 END)",
              "or": 0
            }*/
          ]
        };
      wx.$post(3,url,post).then(res=>{
        if (res.errcode != 0)return;
        let row = res.data.row || [],
          lastGroup = row[row.length - 1 ],
          data = lastGroup && lastGroup.process;
        //有数-已提交
        if (lastGroup && data && data.length){
          resolve({data,state: lastGroup.process_ed_state},)
        }
        //无数-未提交
        else{
          resolve({data: ''});
        }
      })
    })
  },

  //刷新列表
  refreshList(){
    const pages = getCurrentPages();//获取页面栈
    const beforePage = pages[pages.length - 2];  //前一个页面
    beforePage.refreshData(this.data.status);
  },

  getOptionsList(arg){
    let [key,v,url,post,method] = arg;
    return new Promise((resolve,reject) => {
      if (method === 'get'){
        wx.$get(v,url).then(res=>{
          if (res.errcode != 0){
            reject();
            return;
          }
          let data = res.data.row || [],
            list = data;
          resolve({[key]: list});

        });
        return;
      }
      wx.$post(v, url, post).then(res=>{
        if (res.errcode != 0){
          reject();
          return;
        }
        let data = res.data.row || [],
          list = data;
        resolve({[key]: list});
      });
    });

  },
  ready(options){
    let parmaArr = [
        ['followup_type_row_id',1,'AllFollowup/query_all_followup_type',{"row_id": 0},'post'],  //类别
        ['followup_progress_row_id',1,'AllFollowup/query_all_followup_progress',{"row_id": 0},'post'],  //进度
        ['followup_tag_row_id',1,'AllFollowup/query_all_followup_tag',{"row_id": 0},'post'],  //标签
        ['followup_table_id',1,'AllFollowup/query_all_followup_entity',{"row_id": 0},'post'],  //跟进模块
        ['order_client_id',3,'Customer/select_customer',{},'get'],  //跟进客户
      ],
      pmArr = [];
    wx.$each(parmaArr,(i,item)=>{
      pmArr.push(this.getOptionsList(item));
    });
    Promise.all(pmArr.map(p => p.catch(err => ''))).then(res=>{
      let resObj = {};

      wx.$each(res,(i,item)=>{
        resObj = {...resObj,...item}
      });
      let fieldList = this.data.fieldList;
      wx.$each(fieldList,(i,item)=>{
        if (resObj[item.field_id]){
          item.optionList = resObj[item.field_id];
        }
      });
      let progressRequired,tagRequire;
      progressRequired = resObj.followup_progress_row_id[0] && resObj.followup_progress_row_id[0].is_required;
      tagRequire = resObj.followup_tag_row_id[0] && resObj.followup_tag_row_id[0].is_required;
      this.setData({fieldList,progressRequired,tagRequire, status: options.status});

      if (options.rid){

        this.getData(options.rid);
      }
    });

    //获取用户列表
    this.getOptionsList(['user_list',3,'BaseTable/select_user',{},'get']).then(res=>{
      this.setData({
        ['fieldList[6].optionList']: res.user_list
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.$setBarTitle();
    this.ready(options);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
